#!/usr/bin/env python
# -*- coding:utf-8 -*-
from django import forms
from django.conf import settings


class StarkImageFormField(forms.ImageField):

    def __init__(self, width='100px', height='100px', *args, **kwargs):
        kwargs.update({'widget': StarkImageWidget(width=width, height=height)})
        super(StarkImageFormField, self).__init__(*args, **kwargs)


class StarkImageWidget(forms.FileInput):
    template_name = 'stark/plugins/stark-image-field/image-field.html'

    class Media:
        js = (
            'stark/plugins/stark-image-field/image-field.js',
        )
        css = {
            'all': ('stark/plugins/stark-image-field/image-field.css',),
        }

    def __init__(self, width='100px', height='100px', *args, **kwargs):
        super(StarkImageWidget, self).__init__(*args, **kwargs)

        self.width = width
        self.height = height

    def get_context(self, name, value, attrs):
        context = {
            'widget': {
                'name': name,
                'is_hidden': self.is_hidden,
                'required': self.is_required,
                'value': self.format_value(value),
                'attrs': self.build_attrs(self.attrs, attrs),
                'type': self.input_type,
                'img_src': value,
                'img_width': self.width,
                'img_height': self.height,
                'media_url': settings.MEDIA_URL
            }
        }

        return context

    def value_from_datadict(self, data, files, name):
        "File widgets take data from FILES, not POST"
        return files.get(name)
